﻿namespace IFoxCAD.WPF;

/// <summary>
/// 枚举绑定列表源
/// </summary>
public class EnumBindingItemSourceExtension : MarkupExtension
{
    public EnumBindingItemSourceExtension()
    {
    }

    public EnumBindingItemSourceExtension(Type enumType)
    {
        EnumType = enumType;
    }

    private Type? _enumType;

    /// <summary>
    /// 枚举类型
    /// </summary>
    /// <exception cref="ArgumentException">绑定的类型应为枚举</exception>
    public Type? EnumType
    {
        get => _enumType;
        set
        {
            if (_enumType != value && value is not null)
            {
                var type = Nullable.GetUnderlyingType(value) ?? value;
                if (!type.IsEnum)
                    throw new ArgumentException("绑定的类型必须为枚举");
            }

            _enumType = value;
        }
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (_enumType is null)
        {
            throw new InvalidOperationException("未设置EnumType类型");
        }

        var type = Nullable.GetUnderlyingType(_enumType) ?? _enumType;
        var enumValues = Enum.GetValues(type);
        if (type == _enumType)
        {
            return enumValues;
        }

        var tempArray = Array.CreateInstance(type, enumValues.Length + 1);
        enumValues.CopyTo(tempArray, 1);
        return tempArray;
    }
}